package com.sigmazero13.gameutils.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;

import com.sigmazero13.gameutils.model.GameInfo;

public class GameListAdapter extends ArrayAdapter<GameInfo> {
	
	private ArrayList<GameInfo> games;
	private ArrayList<GameInfo> filtered;
	private Filter filter;
	
	public GameListAdapter(Context context, int textViewResourceId, List<GameInfo> games) {
		super(context, textViewResourceId, games);
		this.games = new ArrayList<GameInfo>(games);
		this.filtered = this.games;
	}
	
	@Override
	public Filter getFilter() {
		if (filter == null) 
			filter = new GameFilter();
		return filter;
	}
	
	private class GameFilter extends Filter {
		
		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults result = new FilterResults();
			if (constraint != null && constraint.toString().trim().length() > 0) {
				constraint = constraint.toString().toLowerCase();
				
				String[] info = constraint.toString().split(";",-1);
				String name = info[0];
				Integer players = null;
				Integer maxLength = null;
				try {
					players = Integer.parseInt(info[1]);
				} catch (Exception e) {}
				try {
					maxLength = Integer.parseInt(info[2]);
				} catch (Exception e) {}
				
				ArrayList<GameInfo> filt = new ArrayList<GameInfo>();
				ArrayList<GameInfo> all = new ArrayList<GameInfo>();
				synchronized(this) {
					all.addAll(games);
				}
				for (GameInfo game : all) {
					boolean match = true;
					
					if (name != null && name.trim().length() > 0) {
						if (!game.getName().toLowerCase().contains(name))
							match = false;
					}
					if (players != null) {
						if (players < game.getMinPlayers() || players > game.getMaxPlayers())
							match = false;
					}
					if (maxLength != null) {
						if (maxLength < game.getBggLength())
							match = false;
					}
					
					if (match)
						filt.add(game);
				}
				result.count = filt.size();
				result.values = filt;
			} else {
				synchronized(this) {
					result.values = games;
					result.count = games.size();
				}
			}
			
			return result;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			filtered = (ArrayList<GameInfo>)results.values;
			notifyDataSetChanged();
			clear();
			for (GameInfo game : filtered) 
				add(game);
			notifyDataSetInvalidated();
		}
		
	}

}
